from fastapi import APIRouter, HTTPException

from api.user.form import UserCreateForm, UserDeleteForm
from api.user.models import User
from api.user.serializer import UserCreateSerializer, UserListSerializer

user = APIRouter(prefix="/user", tags=["user接口路由"])


@user.get("/index", response_model=UserListSerializer)
async def get_msg():
    messages = await User.all()
    result = {"users": messages}
    return result


@user.post("/create", response_model=UserCreateSerializer)
async def create_msg(message_in: UserCreateForm):
    message = User(content=message_in.content, kind=message_in.kind, addr=message_in.addr)
    await message.save()
    return message


@user.patch("/update/{msg_id}", response_model=UserCreateSerializer)
async def create_msg(msg_id: int, message_in: UserCreateForm):
    message = await User.get_or_none(id=msg_id)
    if not message:
        raise HTTPException(status_code=404, detail=f"user {msg_id} not found")
    await message.update_from_dict(message_in.dict())
    await message.save()
    return message


@user.patch("/update")
async def create_msg(message_in1: UserCreateForm, message_in2: UserCreateForm):
    flag = False
    message = None
    for key, val in message_in1.dict(exclude_unset=True).items():
        if not flag:
            flag = True
            message = User.all()
        message = message.filter(**{key: val})
    if message:
        await message.update(**message_in2.dict(exclude_unset=True))
    return {"success": "更新成功"}


@user.delete("/delete/{msg_id}")
async def create_msg(msg_id: int):
    message = await User.get_or_none(id=msg_id)
    if message:
        await message.delete()
    return {"success": "删除成功"}


@user.delete("/delete")
async def create_msg(message_in: UserDeleteForm):
    message = User.all()
    for key, val in message_in.dict().items():
        if val is not None:
            message = message.filter(**{key: val})
    if message:
        await message.delete()
    return {"success": "删除成功"}
